/**
 *
 */
package com.shengruan.index.action;

import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.Cookie;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shengruan.admin.jdbc.BidHistoryJdbc;
import com.shengruan.admin.jdbc.UserAccountJdbc;
import com.shengruan.admin.jdbc.UserJdbc;
import com.shengruan.admin.jdbc.UserMessageJdbc;
import com.shengruan.admin.vo.BidHistory;
import com.shengruan.admin.vo.User;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.common.Md5;
import com.shengruan.common.OnLineUser;
import com.shengruan.common.OnlineCounter;
import com.shengruan.common.Visitor;
import com.shengruan.framework.util.AuthFactory;


public class LoginAction extends BaseAction {

    Logger logger = LoggerFactory.getLogger(getClass());

    private UserJdbc userJdbc = (UserJdbc) this.getJdbc(UserJdbc.class);
    private UserAccountJdbc userAccountJdbc = (UserAccountJdbc) this.getJdbc(UserAccountJdbc.class);
    private BidHistoryJdbc bidHistoryJdbc = (BidHistoryJdbc) this.getJdbc(BidHistoryJdbc.class);
    private UserMessageJdbc userMessageJdbc = (UserMessageJdbc) this.getJdbc(UserMessageJdbc.class);


    /**
     * 初始化页面的元素信息
     *
     * @param userName
     * @param password
     */
    private void setParameterAttribute(String userName, String password) {
        this.setRequest("userName", StringUtils.trim(userName));
        this.setRequest("password", StringUtils.trim(password));
    }


    /**
     * 加载用户登录页面
     *
     * @throws Exception
     */
    public void load() throws Exception {
        this.forward("/login.jsp");
    }

    public static void main(String [] args)
    {
    	System.out.println(AuthFactory.decryptPassword("8a48a6cd910c2997bf23fffec94c30a78eebc698d4e52e9ad8126d0f54df818f")); 
    	Md5 md5 = new Md5();
    	System.out.println(md5.getMD5ofStr("admin123"));
    }
    /**
     * 用户登录
     *
     * @throws Exception
     */
    public void login() throws Exception {
        String userName = this.input("userName");
        String password = this.input("password");
        String code = this.input("code");
        String rememberMe = this.input("rememberMe");

        if(null != this.getCurrentUser()) {
            userName = this.getCurrentUser().getUserName();
            password = this.getCurrentUser().getPassword();
        }else {
            if (StringUtils.isEmpty(userName)) {
                setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                this.setRequest(Constants.MESSAGE, "请输入会员名");
                this.forward("/login.jsp");
                return;
            }
            if (StringUtils.isEmpty(password)) {
                setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                this.setRequest(Constants.MESSAGE, "请输入会员密码");
                this.forward("/login.jsp");
                return;
            }
            if (StringUtils.isEmpty(code)) {
                setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                this.setRequest(Constants.MESSAGE, "请输入验证码");
                this.forward("/login.jsp");
                return;
            }

            //校验验证码
            String validateCode = (String) this.request.getSession().getAttribute("validateCode");
            if (StringUtils.isEmpty(validateCode) || !code.equalsIgnoreCase(validateCode)) {
                setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                this.setRequest(Constants.MESSAGE, "验证码不正确");
                this.forward("/login.jsp");
                return;
            }
        }





        User user = userJdbc.getByUserName(userName);
        if (null != user) {

            AuthFactory.passwordKey = Constants.passwordKey;
            int userId = user.getId();
            int loginAttempts = user.getLoginAttempts();


            if (AuthFactory.decryptPassword(user.getPassword()).equalsIgnoreCase(password)) {

                //如果用户登录尝试次数登录6次
                if (loginAttempts == 6) {
                    try {
                        long subtract = (new Date().getTime() - (DateUtils.parseDate(DateFormatUtils.format(Long.valueOf(user.getLoginTime()), "yyyy-MM-dd HH:mm:ss"), new String[]{"yyyy-MM-dd HH:mm:ss"})).getTime()) / (60 * 1000);
                        //用户当前锁定还是一小时之内
                        if (subtract < 60) {
                            setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                            this.setRequest(Constants.MESSAGE, "该用户账号已被锁定，请1个小时后登录。");
                            this.forward("/login.jsp");
                            return;
                        } else {
                            //用户登录成功，更新用户信息
                            user.setLoginAttempts(1);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }



                PropertiesConfiguration config = new PropertiesConfiguration("auction.properties");
                int user_first_login_gift_bid = config.getInt("user.first.login.gift.bid");
                int user_second_login_gift_bid = config.getInt("user.second.login.gift.bid");
                int user_daily_login_gift_bid = config.getInt("user.daily.login.gift.bid");

                //如果用户是第一次登录网站
                if (user.getLogins() == 0) {
                    if(user_first_login_gift_bid > 0) {
                        //第一次赠送3标，1:表示注册赠标
                        userAccountJdbc.presentationBidding(userId, user_first_login_gift_bid, 1);
                        userMessageJdbc.save(userId, "系统赠送客户账户"+user_first_login_gift_bid+"个投标", "系统赠送客户账户"+user_first_login_gift_bid+"个投标");
                    }
                }

                //如果用户不是第一次，要执行赠送第二标的逻辑
                if(user_second_login_gift_bid > 0) {
                    if (bidHistoryJdbc.isSecondBidding(userId)) {
                        BidHistory bidhistory = bidHistoryJdbc.getByUserId(userId);
                        long subtract = (new Date().getTime() - bidhistory.getCreationTime()) / (24 * 60 * 1000);
                        if (subtract > 24) {
                            //第二次赠送2标，1:表示注册赠标
                            userAccountJdbc.presentationBidding(userId, user_second_login_gift_bid, 1);
                            userMessageJdbc.save(userId, "系统赠送客户账户"+user_second_login_gift_bid+"个投标", "系统赠送客户账户"+user_second_login_gift_bid+"个投标");
                        }
                    }
                }

                //每次登陆赠送5标
                if(user_daily_login_gift_bid > 0 && user.getLogins() > 1) {
                    long subtract = (new Date().getTime() - user.getLoginTime()) / (24 * 60 * 1000);
                    if(subtract > 24) {
                        //每次登陆赠送标，3:表示登陆赠标
                        userAccountJdbc.presentationBidding(userId, user_daily_login_gift_bid, 3);
                        userMessageJdbc.save(userId, "系统赠送客户账户"+user_daily_login_gift_bid+"个投标", "系统赠送客户账户"+user_daily_login_gift_bid+"个投标");
                    }
                }

                user.setLogins(user.getLogins() + 1);
                user.setLoginIP(request.getRemoteAddr());
                user.setLoginTime(System.currentTimeMillis());
                userJdbc.update(user);


                
                this.setSession("autoAuctionState", user.getAutoAuctionState());
                /***加到在线用户***/
                OnLineUser.addUser(user);
                

                /***删除游客****/
                Visitor visitor = (Visitor) request.getSession().getAttribute("onLineUser");
                OnlineCounter.removeUser(visitor);
                request.getSession().setAttribute("onLineUser", null);


                //记录客户端Cookie中
                if (StringUtils.isNotEmpty(rememberMe)) {
                    if (rememberMe.equals("true")) {
                        Cookie cookie = new Cookie(Constants.COOKIE_REMEMBERME_KEY, user.getUserName() + "==" + user.getPassword());
                        cookie.setMaxAge(60 * 60 * 24 * 14);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }

                int userMessageCount = userMessageJdbc.getRows(user.getId(), Constants.STATUS_INACTIVE);
                this.setSession(Constants.USER_MESSAGE_COUNT, userMessageCount);

                if(null != this.getCurrentUser()) {
                    this.setSession(Constants.USER, user);
                    this.forward("/RegistrationSuccess.jsp");
                    return;
                }else {
                    this.setSession(Constants.USER, user);
                    this.redirect("/index.ac");
                    return;
                }

            } else {

                //如果用户登录尝试次数登录6次
                if (loginAttempts == 6) {
                    try {
                        long subtract = (new Date().getTime() - (DateUtils.parseDate(DateFormatUtils.format(Long.valueOf(user.getLoginTime()), "yyyy-MM-dd HH:mm:ss"), new String[]{"yyyy-MM-dd HH:mm:ss"})).getTime()) / (60 * 1000);
                        //用户当前锁定还是一小时之内
                        if (subtract < 60) {
                            setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                            this.setRequest(Constants.MESSAGE, "该用户账号已被锁定，请1个小时后登录。");
                            this.forward("/login.jsp");
                            return;
                        } else {
                            user.setLoginAttempts(1);
                            user.setLoginIP(request.getRemoteAddr());
                            user.setLoginTime(System.currentTimeMillis());
                            userJdbc.update(user);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                } else {
                    //如果用户登录失败，用户的登录尝试次数每次加1
                    this.setRequest(Constants.MESSAGE, "用户还剩下[" + (6 - loginAttempts) + "]次重新输入用户名密码的机会");

                    //更新用户的登录次数
                    user.setLoginAttempts(++loginAttempts);
                    user.setLoginIP(request.getRemoteAddr());
                    user.setLoginTime(System.currentTimeMillis());
                    userJdbc.update(user);

                    setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
                    this.forward("/login.jsp");
                }
            }
        } else {
            setParameterAttribute(StringUtils.trim(userName), StringUtils.trim(password));
            this.setRequest(Constants.MESSAGE, "用户不存在请重新输入");
            this.forward("/login.jsp");
        }
    }
}
